﻿using System;
using System.Collections.Generic;

using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace QiuShiBaiKe.Commons
{
    public class CommonHelper
    {
        /// <summary>
        /// 计算给定字符串的md5植
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string CalcMD5(string str)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(str);
            return CalcMD5(bytes);
        }

        public static string CalcMD5(Stream stream)
        {
            using (MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider())
            {
                StringBuilder builder = new StringBuilder();
                byte[]bytes = provider.ComputeHash(stream);

                foreach (byte b in bytes)
                    builder.Append(b.ToString("x2").ToLower());

                return builder.ToString();
            }
        }

        public static string CalcMD5(byte[] bytes)
        {
            using (MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider())
            {
                StringBuilder builder = new StringBuilder();

                bytes = provider.ComputeHash(bytes);

                foreach (byte b in bytes)
                    builder.Append(b.ToString("x2").ToLower());

                return builder.ToString();
            }
        }

        /// <summary>
        /// 从字符串str中截取出长度最多为maxLength的字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="maxLength"></param>
        /// <returns></returns>
        public static string CutString(string str, int maxLength)
        {
            return str.Substring(0, Math.Min(maxLength,str.Length));
        }

    }
}
